package com.contract.spirit.ui.main

import android.app.Activity
import android.content.Intent
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import com.azhon.appupdate.manager.DownloadManager
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.util.CommonUtils
import com.contract.commonlib.util.ext.gsonToJson
import com.contract.spirit.R
import com.contract.spirit.databinding.ActivityMainBinding
import com.contract.spirit.func.FrgViewPagerAdapter
import com.contract.spirit.manage.AppVersionUpdateManager
import com.contract.spirit.manage.CommonConfigManager
import com.contract.spirit.ui.main.first.MainFirstPageFrg
import com.contract.spirit.ui.main.my.MainMyFrg
import com.contract.spirit.ui.splash.SplashViewModel

class MainActivity : BaseActivity<ActivityMainBinding, SplashViewModel>() {
    private val frgList = mutableListOf<Fragment>()
    override fun setContentView(): Int {
        return R.layout.activity_main
    }

    override fun initData() {
        mBinding.apply {
            frgList.add(MainFirstPageFrg())
            frgList.add(MainMyFrg())
            viewpager.adapter = FrgViewPagerAdapter(supportFragmentManager,frgList)
            tabLayout.setViewPager(viewpager)
            viewpager.offscreenPageLimit = frgList.size
        }
    }

    companion object{
        fun launch(activity: Activity){
            activity.startActivity(Intent(activity,MainActivity::class.java))
        }
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val isExit: Boolean = CommonUtils.exitApp(keyCode)
        return if (!isExit) {
            super.onKeyDown(keyCode, event)
        } else isExit
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        mViewModel.versionInfoResponse.observe(this,{ it ->
            parseState(it,{
                CommonConfigManager.configInfo = gsonToJson(it)
                AppVersionUpdateManager.checkUpdata(mContext,it)
            })
        })
    }

    override fun onResume() {
        super.onResume()
        if (!DownloadManager.getInstance(mContext).isDownloading){
            mViewModel.checkAppUpdate()
        }
    }
}